package controller

import (
	"errors"
	"fmt"
	"gitee.com/cheneylau/components/web-server/global"
	"gitee.com/cheneylau/components/web-server/model"
	"github.com/cheneylew/gotools/tool"
	"github.com/gin-gonic/gin"
	"os"
	"path"
)

func HospitalList(c *gin.Context)  {
	res, err := BaseListData(c)
	defer EchoJsonList(c, res, err)
	a, _ := tool.ArrToInterfaces(global.ObserveList)
	res.Data = a
}

func HospitalAdd(c *gin.Context)  {
	res, err := BaseListData(c)
	defer EchoJsonList(c, res, err)
	username := c.PostForm("username")
	keshi := c.PostForm("keshi")
	doctor := c.PostForm("doctor")
	if username == "" || keshi== "" || doctor=="" {
		*err = errors.New("关键信息不能为空!")
		return
	}
	for _, item := range global.ObserveList {
		if item.WhoYuYue == username && item.KeShiName == keshi && doctor == item.DoctorName {
			*err = errors.New("已存在相同的监控，请勿重复添加")
			return
		}
	}
	newObj := model.ObserveInfo{
		WhoYuYue:   username,
		KeShiName:  keshi,
		DoctorName: doctor,
		HopeDate:   "",
	}
	global.ObserveList = append(global.ObserveList, newObj)
	save()
	//db.SQLite.Create(&newObj)
}

func HospitalDelete(c *gin.Context)  {
	res, err := BaseListData(c)
	defer EchoJsonList(c, res, err)

	username := c.PostForm("name")
	keshi := c.PostForm("keshi")
	doctor := c.PostForm("doctor")

	deleteIndex := -1
	for index, item := range global.ObserveList {
		if item.WhoYuYue == username && item.KeShiName == keshi && doctor == item.DoctorName {
			//删除
			deleteIndex = index
		}
	}
	if deleteIndex != -1{
		global.ObserveList = append(global.ObserveList[:deleteIndex], global.ObserveList[deleteIndex+1:]...)
		save()
	}
}

func save()  {
	s := "预约人 科室 专家\r\n"
	for _, item := range global.ObserveList {
		s += fmt.Sprintf("%s %s %s\r\n",item.WhoYuYue, item.KeShiName, item.DoctorName)
	}
	tool.WriteFile(path.Dir(os.Args[0])+"/app.conf", s)
}
